package com.sq.shortlink.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sq.shortlink.admin.common.biz.user.UserContext;
import com.sq.shortlink.admin.common.convension.result.Result;
import com.sq.shortlink.admin.dao.entity.GroupDO;
import com.sq.shortlink.admin.dao.mapper.GroupMapper;
import com.sq.shortlink.admin.dto.req.ShortLinkGroupDeleteReq;
import com.sq.shortlink.admin.dto.req.ShortLinkGroupRespDTO;
import com.sq.shortlink.admin.dto.req.ShortLinkGroupSortReq;
import com.sq.shortlink.admin.dto.req.ShortLinkGroupUpdateReq;
import com.sq.shortlink.admin.remoto.ShortLinkRemoteService;
import com.sq.shortlink.admin.remoto.dto.resp.ShortLinkGroupQueryCountRespDTO;
import com.sq.shortlink.admin.service.GroupService;
import com.sq.shortlink.admin.toolkit.RandomStringGenerator;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 短链接分组接口实现层
 * @author quan
 */
@Service
public class GroupServiceImpl extends ServiceImpl<GroupMapper, GroupDO> implements GroupService {

    @Override
    public void saveGroup(String name) {
        saveGroup(UserContext.getUsername(),name);
    }

    @Override
    public void saveGroup(String username,String name) {
        String gid;
        do {
            gid = RandomStringGenerator.generateRandomString(6);
        } while (!hasGid(username,gid));
        GroupDO groupDO = GroupDO.builder()
                .name(name)
                .gid(gid)
                .sortOrder(0)
                .username(username)
                .build();
        baseMapper.insert(groupDO);
    }

    @Override
    public List<ShortLinkGroupRespDTO> listGroup() {
        LambdaQueryWrapper<GroupDO>  queryWrapper = Wrappers.lambdaQuery(GroupDO.class)
                .eq(GroupDO::getDelFlag,0)
                .eq(GroupDO::getUsername, UserContext.getUsername())
                .orderByDesc(GroupDO::getSortOrder, GroupDO::getUpdateTime);
        List<GroupDO> groupDOList = baseMapper.selectList(queryWrapper);
        List<ShortLinkGroupRespDTO> shortLinkGroupRespDTOList
                = BeanUtil.copyToList(groupDOList, ShortLinkGroupRespDTO.class);
        ShortLinkRemoteService shortLinkRemoteService = new ShortLinkRemoteService() {
        };
        Result<List<ShortLinkGroupQueryCountRespDTO>> listGroupShortLinkCount = shortLinkRemoteService
                .listGroupShortLinkCount(groupDOList.stream().map(GroupDO::getGid).collect(Collectors.toList()));
        Map<String, Integer> collect = listGroupShortLinkCount.getData().stream()
                .collect(Collectors.toMap(ShortLinkGroupQueryCountRespDTO::getGid, ShortLinkGroupQueryCountRespDTO::getShortLinkCount));
        shortLinkGroupRespDTOList.stream().forEach(shortLinkGroupRespDTO -> {
            shortLinkGroupRespDTO.setShorLinkCount(collect.get(shortLinkGroupRespDTO.getGid()));
        });
        return shortLinkGroupRespDTOList;
    }

    @Override
    public void updateGroup(ShortLinkGroupUpdateReq requestParam) {
        LambdaUpdateWrapper<GroupDO> updateWrapper = Wrappers.lambdaUpdate(GroupDO.class)
                .eq(GroupDO::getUsername, UserContext.getUsername())
                .eq(GroupDO::getGid, requestParam.getGid())
                .eq(GroupDO::getDelFlag, 0);
        GroupDO groupDO = new GroupDO();
        groupDO.setName(requestParam.getName());
        baseMapper.update(groupDO,updateWrapper);
    }

    @Override
    public void deleteGroup(ShortLinkGroupDeleteReq requestParam) {
        LambdaUpdateWrapper<GroupDO> updateWrapper = Wrappers.lambdaUpdate(GroupDO.class)
                .eq(GroupDO::getDelFlag, 0)
                .eq(GroupDO::getUsername, UserContext.getUsername())
                .eq(GroupDO::getGid, requestParam.getGid());
        GroupDO groupDO = new GroupDO();
        groupDO.setDelFlag(1);
        groupDO.setUpdateTime(LocalDateTime.now());
        baseMapper.update(groupDO,updateWrapper);
    }

    @Override
    public void updateGroupSort(List<ShortLinkGroupSortReq> requestParam) {
        requestParam.stream().forEach(item->{
            GroupDO groupDO = GroupDO.builder()
                    .sortOrder(item.getSortOrder())
                    .build();
            LambdaUpdateWrapper<GroupDO> updateWrapper = Wrappers.lambdaUpdate(GroupDO.class)
                    .eq(GroupDO::getDelFlag, 0)
                    .eq(GroupDO::getUsername, UserContext.getUsername())
                    .eq(GroupDO::getGid, item.getGid());
            baseMapper.update(groupDO,updateWrapper);
        });
    }

    /**
     * 检查gid是否可用
     * @param gid 分组标识
     * @return 检查标识 true-可用 false-不可用
     */
    private boolean hasGid(String username,String gid) {
        LambdaQueryWrapper<GroupDO> queryWrapper = Wrappers.lambdaQuery(GroupDO.class)
                .eq(GroupDO::getDelFlag,0)
                .eq(GroupDO::getGid, gid)
                .eq(GroupDO::getUsername, username);
        GroupDO hasGroupFlag = baseMapper.selectOne(queryWrapper);
        return hasGroupFlag == null;
    }
}
